package com.mzj.saas.mservice.sys.service;

import com.alibaba.fastjson.JSON;
import com.mzj.saas.commons.ResultBean;
import com.mzj.saas.commons.StatusCode;
import com.mzj.saas.commons.enums.UserLoginTypeEnum;
import com.mzj.saas.commons.vo.redis.TokenRedisVo;
import com.mzj.saas.mservice.department.entity.Department;
import com.mzj.saas.mservice.department.repository.DepartmentRepository;
import com.mzj.saas.mservice.property.entity.CommunityHouseUser;
import com.mzj.saas.mservice.property.repository.CommunityHouseUserRepository;
import com.mzj.saas.mservice.roles.entity.Role;
import com.mzj.saas.mservice.roles.entity.RolePermission;
import com.mzj.saas.mservice.roles.entity.UserRoleRef;
import com.mzj.saas.mservice.roles.repository.RolePermissionRepository;
import com.mzj.saas.mservice.roles.repository.RoleRepository;
import com.mzj.saas.mservice.roles.repository.UserRoleRefRepository;
import com.mzj.saas.mservice.roles.service.RolesService;
import com.mzj.saas.mservice.sys.entity.AppUser;
import com.mzj.saas.mservice.sys.entity.DepartmentRoleRecord;
import com.mzj.saas.mservice.sys.entity.User;
import com.mzj.saas.mservice.sys.mapper.PermissionRowMapper;
import com.mzj.saas.mservice.sys.repository.AppUserRepository;
import com.mzj.saas.mservice.sys.repository.DepartmentRoleRecordRepository;
import com.mzj.saas.mservice.sys.repository.UserRepository;
import com.mzj.saas.mservice.sys.vo.DepartmentRoleRecordVO;
import com.mzj.saas.mservice.sys.vo.ParamVO;
import com.mzj.saas.mservice.sys.vo.PermissionVO;
import com.mzj.saas.redis.RedisService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class PermissionService {
    private static final Logger LOG = LoggerFactory.getLogger(PermissionService.class);
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private RedisService redisService;
    @Autowired
    private RolesService rolesService;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private DepartmentRepository departmentRepository;
    @Autowired
    private RoleRepository roleRepository;
    @Autowired
    private RolePermissionRepository rolePermissionRepository;
    @Autowired
    private UserRoleRefRepository userRoleRefRepository;
    @Autowired
    private DepartmentRoleRecordRepository departmentRoleRecordRepository;
    @Autowired
    private UserService userService;
    @Autowired
    private AppUserRepository appUserRepository;
    @Autowired
    private CommunityHouseUserRepository communityHouseUserRepository;
    /*
     *获取用户权限
     */
    public ResultBean<List<Map<String, Object>>> getUserPermission(String accessToken,String communityHouseId) {
        ResultBean<List<Map<String, Object>>> result = new ResultBean<>();
        TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
        try {
            if (tokenRedisVo == null) {
                result.setCode(StatusCode.ERROR_CODE_40001.getErrorCode());
                result.setMsg(StatusCode.ERROR_CODE_40001.getErrorMsg());
                return result;
            }
            List<Map<String, Object>> permissionByUser = null;
            // 统一处理用户角色类型：1企业用户、2普通用户
            if (tokenRedisVo.getLoginType() != null && tokenRedisVo.getLoginType() == UserLoginTypeEnum.ENTERPRISE.getValue()) {
                permissionByUser = findPermissionByUser(tokenRedisVo.getId(), tokenRedisVo.getEnterpriseId());
            } else {
                permissionByUser = findPermissionByCommonRoleUser(tokenRedisVo.getEnterpriseId(), tokenRedisVo.getId(), tokenRedisVo.getEnterpriseUserId(),communityHouseId);
            }
            result.setMsg(StatusCode.SUCCESS_CODE_10000.getErrorMsg());
            result.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
            result.setResultData(permissionByUser);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            result.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
            result.setMsg(e.getMessage());
        }
        return result;
    }

    /**
     * 用户权限列表
     *
     * @param Id
     * @param companyId
     * @return
     * @author shun
     * @date 2021年6月23日
     */
    public List<Map<String, Object>> findPermissionByUser(String Id, Long companyId) {
        String sql = "SELECT DISTINCT p.id, p.parent_id, p.name, p.type, p.url, p.method, p.code, p.icon, p.sortby,IF(ur.`role_id`>0,1,0) AS role_id  FROM saas_user_role_ref ur  " +
                "LEFT JOIN saas_role_app_ref rp ON rp.role_id = ur.role_id " +
                "LEFT JOIN saas_permission p ON p.id = rp.permission_id\n" +
                "WHERE ur.user_id = ? AND p.id IS NOT NULL";
        sql += " order by p.sortby, p.name";
        List<PermissionVO> list = jdbcTemplate.query(sql, new Object[]{Id}, new PermissionRowMapper());
        List<Map<String, Object>> menuList = new LinkedList<Map<String, Object>>();

        //管理员标识：true 是，false 否
        Boolean masterFlag = userService.judgeManagerType(Id);
        if (!masterFlag) {
            //获取关闭权限集合
            List<DepartmentRoleRecord> departmentRoleRecords = departmentRoleRecordRepository.findByDeptId(companyId);
            ArrayList<Long> closeChildPermission = new ArrayList<>();
            for (DepartmentRoleRecord departmentRoleRecord : departmentRoleRecords) {
                closeChildPermission.addAll(findCloseChildPermission(departmentRoleRecord.getPermissionId()));
            }

            //过滤企业关闭权限
            if (list != null & list.size() != 0) {
                list = list.stream().filter((PermissionVO s) -> !(closeChildPermission.contains(s.getId())))
                        .collect(Collectors.toList());
            }
        }

        List<UserRoleRef> byUserId = userRoleRefRepository.findByUserId(Id);
        List<Long> roleIds = byUserId.stream().map(UserRoleRef::getRoleId).collect(Collectors.toList());
        List<RolePermission> byRoleId = rolePermissionRepository.findByRoleIdIn(roleIds);
        findChild(menuList, list, byRoleId);
        return menuList;
    }


    /**
     * 普通角色权限列表
     *
     * @param companyId
     * @return
     * @author shun
     * @date 2021年6月23日
     */
    public List<Map<String, Object>> findPermissionByCommonRoleUser(Long companyId, String userId, String enterpriseUserId,String communityHouseId) {
    	AppUser appUser = appUserRepository.findByIdOrEnterpriseUserId(userId, userId);
        String sqls= "SELECT '1' AS TYPE FROM saas_house_match_user u JOIN saas_app_user pu ON u.match_user_id = pu.id "
        		+ "WHERE pu.phone = ? AND pu.status = 1 AND u.status = 1 "
        		+ "UNION ALL "
        		+ "SELECT b.label AS TYPE "
        		+ "FROM  saas_community_house_user a LEFT JOIN m_match_user_house b ON a.community_house_id = b.house_id "
        		+ "WHERE a.status=1 AND a.mobile = ? AND a.type = 1" ;
        List<String> types = jdbcTemplate.queryForList(sqls, String.class, appUser.getPhone(), appUser.getPhone());
        LOG.info(sqls + appUser.getPhone());
        // 获取单位、个人、普通三个角色所有权限
        List<String> unitList = types.stream().filter(uu -> "2".equals(uu)).collect(Collectors.toList());
        List<String> persionList = types.stream().filter(uu -> "1".equals(uu)).collect(Collectors.toList());

        ArrayList<String> roleIdList = new ArrayList<>();
        List<Long> roleIds = new ArrayList<>();
        if(!unitList.isEmpty()){
        	// 查询单位承租人角色权限
        	Long roleId = rolesService.getCommonRoleDeptRoleId();
            if (null != roleId){
                roleIdList.add(String.valueOf(roleId));
                roleIds.add(roleId);
            }
        }
        
        if(!persionList.isEmpty()){
        	// 查询个人承租人角色权限
        	Long roleId = rolesService.getCommonRoleOneRoleId();
            if (null != roleId){
                roleIdList.add(String.valueOf(roleId));
                roleIds.add(roleId);
            }
        }
        
        // 普通默认权限
        if(roleIdList.isEmpty()){
        	Long roleId = rolesService.getDefaultUserRoleId();
            if (null != roleId){
                roleIdList.add(String.valueOf(roleId));
                roleIds.add(roleId);
            }
        }
        LOG.info("权限查询, roleIds={}", JSON.toJSONString(roleIdList));
        if (roleIdList == null || roleIdList.size()<=0) {
            return null;
        }
        String sql = "SELECT DISTINCT p.id, p.parent_id, p.name, p.type, p.url, p.method, p.code, p.icon, p.sortby, rp.role_id  FROM saas_role_app_ref rp "
                + "LEFT JOIN saas_permission p ON p.id = rp.permission_id "
                + "WHERE rp.role_id in ("+String.join(",",roleIdList)+") AND p.id IS NOT NULL";

        List<PermissionVO> permissionList = jdbcTemplate.query(sql, new Object[]{}, new PermissionRowMapper());
        LOG.info(sql);
        List<PermissionVO> list = permissionList.stream().collect(
                Collectors.collectingAndThen(
                        Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(PermissionVO::getId))), ArrayList::new)
        );
        //修复bug，现在用户能有多个房屋，判断用户是否是同住人，如果是就去除住户管理权限
        //通过用户userId和用户的房屋ID进行查询，判断此时用户是否是同住人
        CommunityHouseUser byUserIdAndStatusAndCommunityHouseId = communityHouseUserRepository.findByUserIdAndStatusAndCommunityHouseId(userId, 1, communityHouseId);
        if (byUserIdAndStatusAndCommunityHouseId != null) {
            Integer type = byUserIdAndStatusAndCommunityHouseId.getType();
            if (type == 2) {
                for (int i = 0; i < list.size(); i++) {
                    if (list.get(i).getName().equals("住户管理")) {
                        list.remove(i);
                    }
                }
            }
        }

        List<Map<String, Object>> menuList = new LinkedList<Map<String, Object>>();
        List<RolePermission> byRoleId = rolePermissionRepository.findByRoleIdIn(roleIds);
        findChild(menuList, list, byRoleId);
        return menuList;
    }



//    /**
//     * 普通角色权限列表
//     *
//     * @param Id
//     * @param companyId
//     * @return
//     * @author shun
//     * @date 2021年6月23日
//     */
//    public List<Map<String, Object>> findPermissionByCommonRoleUser(Long companyId) {
//        Long roleId = rolesService.getDefaultUserRoleId();
//        if (roleId == null) {
//            return null;
//        }
//        String sql = "SELECT DISTINCT p.id, p.parent_id, p.name, p.type, p.url, p.method, p.code, p.icon, p.sortby, rp.role_id  FROM saas_role_app_ref rp "
//                + "LEFT JOIN saas_permission p ON p.id = rp.permission_id "
//                + "WHERE rp.role_id = ? AND p.id IS NOT NULL";
//        sql += " order by p.sortby, p.name";
//        List<PermissionVO> list = jdbcTemplate.query(sql, new Object[]{roleId}, new PermissionRowMapper());
//        List<Map<String, Object>> menuList = new LinkedList<Map<String, Object>>();
//        //获取关闭权限集合
//        List<DepartmentRoleRecord> departmentRoleRecords = departmentRoleRecordRepository.findByDeptId(companyId);
//        ArrayList<Long> closeChildPermission = new ArrayList<>();
//        for (DepartmentRoleRecord departmentRoleRecord : departmentRoleRecords) {
//            closeChildPermission.addAll(findCloseChildPermission(departmentRoleRecord.getPermissionId()));
//        }
//        //过滤企业关闭权限
//        if (list != null & list.size() != 0) {
//            list = list.stream()
//                    .filter((PermissionVO s) -> !(closeChildPermission.contains(s.getId())))
//                    .collect(Collectors.toList());
//
//        }
//        findChild(menuList, list);
//        return menuList;
//    }

    private void findChild(List<Map<String, Object>> menuList, List<PermissionVO> list, List<RolePermission> byRoleId) {
        for (PermissionVO vo : list) {
            if (hasParent(vo.getParentId(), list)) {
                continue;
            }
            String url = StringUtils.isEmpty(vo.getUrl()) ? "" : vo.getUrl();
            Map<String, Object> firstMap = new LinkedHashMap<String, Object>();
            firstMap.put("id", vo.getId());
            firstMap.put("parentId", vo.getParentId());
            firstMap.put("type", vo.getType());
            firstMap.put("name", vo.getName());
            firstMap.put("url", url);
            firstMap.put("code", vo.getCode());
            firstMap.put("icon", vo.getIcon());
            //仅作为标识0无权限1有权限
            //firstMap.put("flag", vo.getRoleId() == 0 ? 0 : 1);
            int i = 0;
            for (RolePermission rolePermission : byRoleId) {
                if (vo.getId().equals(rolePermission.getPermissionId())){
                    i = 1;
                    break;
                }
            }
            firstMap.put("flag", i);
            menuList.add(firstMap);
            findChildMenus(firstMap, vo, list, byRoleId);
        }
    }

    /*
     *查找子类
     */
    private void findChildMenus(Map<String, Object> firstMap, PermissionVO parentVo, List<PermissionVO> list, List<RolePermission> byRoleId) {
        if (!hasChildren(parentVo.getId(), list)) {
            return;
        }
        List<Map<String, Object>> childList = new LinkedList<Map<String, Object>>();
        for (PermissionVO vo : list) {
            if (parentVo.getId().longValue() != vo.getParentId().longValue()) {
                continue;
            }
            String url = StringUtils.isEmpty(vo.getUrl()) ? "" : vo.getUrl();


            Map<String, Object> childMap = new LinkedHashMap<String, Object>();
            childMap.put("id", vo.getId());
            childMap.put("parentId", vo.getParentId());
            childMap.put("type", vo.getType());
            childMap.put("name", vo.getName());
            childMap.put("url", url);
            childMap.put("code", vo.getCode());
            childMap.put("icon", vo.getIcon());
            //仅作为标识0无权限1有权限
            //childMap.put("flag", vo.getRoleId() == 0 ? 0 : 1);
            //仅作为标识0无权限1有权限
            int i = 0;
            for (RolePermission rolePermission : byRoleId) {
                if (vo.getId().equals(rolePermission.getPermissionId())){
                    i = 1;
                    break;
                }
            }
            childMap.put("flag", i);
            childList.add(childMap);

            firstMap.put("child", childList);

            if (hasChildren(parentVo.getId(), list)) {
                findChildMenus(childMap, vo, list,byRoleId);
            }
        }
    }

    /*
     *判断是否有父级
     */
    private boolean hasParent(Long id, List<PermissionVO> list) {
        for (PermissionVO vo : list) {
            if (id.longValue() != vo.getId().longValue()) {
                continue;
            }
            return true;
        }
        return false;
    }

    /*
     *判断是否有子集
     */
    private boolean hasChildren(Long id, List<PermissionVO> list) {
        for (PermissionVO vo : list) {
            if (id.longValue() != vo.getParentId().longValue()) {
                continue;
            }
            return true;
        }
        return false;
    }

    /*
     *权限管理列表展示
     */
    public ResultBean<Object> permissionManagerList(String accessToken) {
        LOG.info("PermissionService permissionManagerList accessToken={}", accessToken);
        ResultBean<Object> resultBean = new ResultBean<>();
        resultBean.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
        resultBean.setMsg(StatusCode.SUCCESS_CODE_10000.getErrorMsg());
        resultBean.setResultData(Collections.emptyList());
        TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
        try {
            if (tokenRedisVo == null) {
                resultBean.setCode(StatusCode.ERROR_CODE_40001.getErrorCode());
                resultBean.setMsg(StatusCode.ERROR_CODE_40001.getErrorMsg());
                return resultBean;
            }
            User user = userRepository.findById(tokenRedisVo.getId());
            if (user == null) {
                return ResultBean.failedResultWithMsg("用户不存在或已删除");
            }
            Optional<Department> existDepartmentOptional = departmentRepository.findById(tokenRedisVo.getEnterpriseId());
            if (existDepartmentOptional == null) {
                return ResultBean.failedResultWithMsg("部门信息不存在或已删除");
            }
            /*   Role existRole = roleRepository.findByOrgIdAndType(tokenRedisVo.getEnterpriseId(), 1);
            if (existRole == null) {
                return ResultBean.failedResultWithMsg("主管理员角色信息不存在或已删除");
            }
            List<UserRoleRef> existUserRole = userRoleRefRepository.findByRoleId(existRole.getId());
            if (existUserRole == null) {
                return ResultBean.failedResultWithMsg("主管理员不存在或已删除");
            }*/

            List<UserRoleRef> roleList = userRoleRefRepository.findByUserId(user.getId());
            StringBuffer roleIds = new StringBuffer();
            List<Long> roleS = new ArrayList<>();
            roleList.forEach(r -> {
                roleIds.append(r.getRoleId()).append(",");
                roleS.add(r.getRoleId());
            });

            String roleId = roleIds.toString().substring(0, roleIds.toString().length() - 1);

            //获取当前用户所属的全部角色拥有的权限列表
            /*String sql = " SELECT p.id, p.parent_id, p.name, p.type, p.url, p.method, p.code, p.icon, p.sortby,ref.permission_id AS role_id " +
                    "FROM (SELECT DISTINCT p.id, p.parent_id, p.name, p.type, p.url, p.method, p.code, p.icon, p.sortby FROM  saas_permission p LEFT JOIN saas_role_app_ref   rp ON p.id = rp.permission_id WHERE " +
                    "rp.role_id in (" + roleId + ") ) p LEFT JOIN (SELECT * FROM saas_department_role_record r WHERE r.dept_id=?) ref ON ref.permission_id = p.id  ORDER BY id \n";*/

            String sql = "SELECT p.id, p.parent_id, p.name, p.type, p.url, p.method, p.code, p.icon, p.sortby,ref.permission_id AS role_id\n" +
                    "FROM (\n" +
                    "SELECT DISTINCT p.id, p.parent_id, p.name, p.type, p.url, p.method, p.code, p.icon, p.sortby \n" +
                    "FROM (SELECT p.* FROM saas_permission p \n" +
                    "LEFT JOIN saas_role_app_ref rf ON p.id = rf.permission_id\n" +
                    "LEFT JOIN saas_role r ON rf.role_id = r.id\n" +
                    "WHERE r.org_id = ? AND r.type = 1) p \n" +
                    "LEFT JOIN saas_role_app_ref rp ON p.id = rp.permission_id \n" +
                    "WHERE rp.role_id in (" + roleId + ")\n" +
                    ") p LEFT JOIN (SELECT * FROM saas_department_role_record r WHERE r.dept_id = ?) ref ON ref.permission_id = p.id ORDER BY id";
            List<PermissionVO> query = jdbcTemplate.query(sql, new Object[]{tokenRedisVo.getEnterpriseId(), tokenRedisVo.getEnterpriseId()}, new PermissionRowMapper());
            List<Map<String, Object>> menuList = new LinkedList<Map<String, Object>>();
            List<RolePermission> byRoleId = rolePermissionRepository.findByRoleIdIn(roleS);
            findChild(menuList, query,byRoleId);
            resultBean.setResultData(menuList);
        } catch (Exception e) {
            resultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
            resultBean.setMsg(e.getMessage());
        }
        return resultBean;
    }

    /*
     *权限开关设置
     */
    public ResultBean<Object> permissionOpenCloseButton(String accessToken, ParamVO paramVO) {
        LOG.info("PermissionService permissionOpenCloseButton accessToken={},paramVO={}", accessToken, paramVO);
        ResultBean<Object> resultBean = new ResultBean<>();
        resultBean.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
        resultBean.setMsg(StatusCode.SUCCESS_CODE_10000.getErrorMsg());
        resultBean.setResultData(Collections.emptyList());
        TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
        try {
            if (tokenRedisVo == null) {
                resultBean.setCode(StatusCode.ERROR_CODE_40001.getErrorCode());
                resultBean.setMsg(StatusCode.ERROR_CODE_40001.getErrorMsg());
                return resultBean;
            }
            Optional<Department> existDepartmentOptional = departmentRepository.findById(tokenRedisVo.getEnterpriseId());
            if (existDepartmentOptional == null) {
                return ResultBean.failedResultWithMsg("部门信息不存在或已删除");
            }
            if (paramVO == null) {
                resultBean.setCode(StatusCode.ERROR_CODE_10005.getErrorCode());
                resultBean.setMsg(StatusCode.ERROR_CODE_10005.getErrorMsg());
                return resultBean;
            }
            if (paramVO.getFlag() == null || paramVO.getLongIds() == null) {
                resultBean.setCode(StatusCode.ERROR_CODE_10005.getErrorCode());
                resultBean.setMsg(StatusCode.ERROR_CODE_10005.getErrorMsg());
                return resultBean;
            }
            //权限状态0拥有权限 1没有权限
            Integer flag = paramVO.getFlag();
            List<Long> permissionIds = paramVO.getLongIds();
            //删除-开启权限
            if (flag == 1) {
                for (Long permissionId : permissionIds) {
                    departmentRoleRecordRepository.deleteByDeptIdAndPermissionId(tokenRedisVo.getEnterpriseId(), permissionId);
                }
            } else {
                //新增-关闭权限
                DepartmentRoleRecordVO departmentRoleRecordVO = new DepartmentRoleRecordVO();
                departmentRoleRecordVO.setDeptId(tokenRedisVo.getEnterpriseId());
                Role existRole = roleRepository.findByOrgIdAndType(tokenRedisVo.getEnterpriseId(), 1);
                if (existRole == null) {
                    return ResultBean.failedResultWithMsg("主管理员角色信息不存在或已删除");
                }
                for (Long permissionId : permissionIds) {
                    departmentRoleRecordVO.setPermissionId(permissionId);
                    DepartmentRoleRecord departmentRoleRecord = new DepartmentRoleRecord();
                    BeanUtils.copyProperties(departmentRoleRecordVO, departmentRoleRecord);
                    departmentRoleRecordRepository.save(departmentRoleRecord);
                }
            }
        } catch (Exception e) {
            resultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
            resultBean.setMsg(e.getMessage());
        }
        return resultBean;
    }

    /*
     *角色的权限列表显示
     */
    public ResultBean<Object> rolePermissionList(String accessToken, Long roleId) {
        LOG.info("RolesService rolePermissionList accessToken={},roleId", accessToken, roleId);
        ResultBean<Object> result = new ResultBean<>();
        result.setMsg(StatusCode.SUCCESS_CODE_10000.getErrorMsg());
        result.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
        TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
        Long enterpriseId = tokenRedisVo.getEnterpriseId();
        try {
            if (tokenRedisVo == null) {
                result.setCode(StatusCode.ERROR_CODE_40001.getErrorCode());
                result.setMsg(StatusCode.ERROR_CODE_40001.getErrorMsg());
                return result;
            }
            if (roleId == null) {
                result.setCode(StatusCode.ERROR_CODE_10005.getErrorCode());
                result.setMsg(StatusCode.ERROR_CODE_10005.getErrorMsg());
                return result;
            }
            User existUser = userRepository.findById(tokenRedisVo.getId());
            if (existUser == null) {
                return ResultBean.failedResultWithMsg("用户信息不存在或已删除！");
            }
            //查询选中角色的权限列表
            /*String sql = "SELECT DISTINCT p.id, p.parent_id, p.name, p.type, p.url, p.method, p.code, p.icon, p.sortby,ref.role_id \n" +
                    "FROM saas_permission p LEFT JOIN (SELECT * FROM saas_role_app_ref r WHERE r.role_id = ?) ref ON ref.permission_id = p.id\n";*/

            //之前的sql语句查询慢，下面是优化过后的sql
            // String sql = "SELECT DISTINCT p.id, p.parent_id, p.name, p.type, p.url, p.method, p.code, p.icon, p.sortby,ref.role_id  \n" +
            //         "FROM (SELECT p.* FROM saas_permission p \n" +
            //         "LEFT JOIN saas_role_app_ref rf ON p.id = rf.permission_id\n" +
            //         "LEFT JOIN saas_role r ON rf.role_id = r.id\n" +
            //         "WHERE r.org_id = ? AND r.type = 1) p \n" +
            //         "LEFT JOIN (SELECT * FROM saas_role_app_ref r WHERE r.role_id = ?) ref ON ref.permission_id = p.id\n";
            // List<PermissionVO> list = jdbcTemplate.query(sql, new Object[]{tokenRedisVo.getEnterpriseId(), roleId}, new PermissionRowMapper());
            String sql = "SELECT DISTINCT p.id, p.parent_id, p.name, p.type, p.url, p.method, p.code, p.icon, p.sortby,rf.role_id  \n" +
                    " FROM saas_permission p \n" +
                    "LEFT JOIN saas_role_app_ref rf ON p.id = rf.permission_id\n" +
                    "LEFT JOIN saas_role r ON rf.role_id = r.id\n" +
                    "WHERE r.org_id = ? AND r.type = 1";
            List<PermissionVO> list = jdbcTemplate.query(sql, new Object[]{tokenRedisVo.getEnterpriseId()}, new PermissionRowMapper());
            List<Map<String, Object>> menuList = new LinkedList<Map<String, Object>>();

            //获取关闭权限集合
            List<DepartmentRoleRecord> departmentRoleRecords = departmentRoleRecordRepository.findByDeptId(tokenRedisVo.getEnterpriseId());
            ArrayList<Long> closeChildPermission = new ArrayList<>();
            for (DepartmentRoleRecord departmentRoleRecord : departmentRoleRecords) {
                closeChildPermission.addAll(findCloseChildPermission(departmentRoleRecord.getPermissionId()));
            }

            //过滤企业关闭权限
            if (list != null & list.size() != 0) {
                list = list.stream().filter((PermissionVO s) -> !(closeChildPermission.contains(s.getId()))).collect(Collectors.toList());
            }
            list = list.stream().distinct().collect(Collectors.toList());
            List<RolePermission> byRoleId = rolePermissionRepository.findByRoleId(roleId);
            findChild(menuList, list, byRoleId);
            result.setResultData(menuList);

        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            result.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
            result.setMsg(e.getMessage());
        }
        return result;
    }

    /*
     *查找查找当前关闭权限及其所有关闭权限的子集权限id
     */
    public List<Long> findCloseChildPermission(Long id) {
        List<Long> longList = new ArrayList<>();
        longList.add(id);
        String sql = " SELECT id FROM ( SELECT t1.id,IF(FIND_IN_SET(parent_id, @pids) > 0,@pids := CONCAT(@pids, ',', id),0) AS ischild FROM ( SELECT id,parent_id FROM `saas_permission` t ORDER BY parent_id, id ) t1,(SELECT @pids := ? ) t2 ) t3 WHERE ischild != 0 \n";
        longList.addAll(jdbcTemplate.queryForList(sql, new Object[]{id}, Long.class));
        return longList;
    }


}
